//
//  KYUserInfoController.m
//  KYKJPackDemo
//
//  Created by Jordan zhou on 2017/10/10.
//  Copyright © 2017年 ???. All rights reserved.
//

#import "KYUserInfoController.h"
#import "KYTextView.h"
#import "KYRadioBoxChooseView.h"
#import "KYDatePickerView.h"

@interface KYUserInfoController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,UITextViewDelegate,UIScrollViewDelegate,UIAlertViewDelegate, UIActionSheetDelegate,KYRadioBoxChooseViewDelegate,KYDatePickerViewDelegate>
@property (nonatomic, weak) KYTextView *textView;

@property (nonatomic, strong) KYSettingArrowItem *icon;

@property (nonatomic, strong) KYSettingItem *nick;

@property (nonatomic, strong) KYSettingItem *sex;

@property (nonatomic, strong) KYSettingItem *birth;

@property (nonatomic, strong) UIImage *chooseImage;
@end

@implementation KYUserInfoController

- (void)viewDidLoad {
    
    [super viewDidLoad];
  
    // 1.添加分组
    [self setUpGroup0];
    
    // 2.设置导航栏右边保存按钮
    [self setUpRightNavItem];
    
    // 3.创建footer
    [self setUpFooterView];
}

#pragma mark - setUp
- (void)setUpFooterView
{
    // 1.添加
    KYTextView *textView = [[KYTextView alloc] init];
    textView.font = [UIFont systemFontOfSize:15.5f];
    textView.frame = CGRectMake(6, 0, self.tableView.frame.size.width - 12, 90);
    // 垂直方向上永远可以拖拽
    textView.alwaysBounceVertical = YES;
    textView.delegate = self;
    textView.backgroundColor = [UIColor whiteColor];
    
    if ([KYUserAccountTool shareUserData].userIntro.length) {
        textView.text = [KYUserAccountTool shareUserData].userIntro;
    } else {
        textView.placeholder = @"个性签名...";
    }
    self.textView = textView;
    
    // 2.用view包装然后设置footer
    UIView *footer = [[UIView alloc] init];
    CGFloat footerH = 90;
    footer.frame = CGRectMake(0, 0, 0, footerH);
    [footer addSubview:textView];
    self.tableView.tableFooterView = footer;
}

- (void)setUpRightNavItem
{
    self.navigationItem.rightBarButtonItem = [UIBarButtonItem itemWithTitle:NSLocalizedString(@"保存", nil) titleColor:[UIColor blackColor] target:self action:@selector(save)];
}

- (void)setUpGroup0
{
    __weak typeof(self) selfVc = self;

    KYSettingGroup *group = [self addGroup];
    
    KYSettingArrowItem *icon = [KYSettingArrowItem itemWithTitle:NSLocalizedString(@"头像", nil) destVcClass:nil];
    icon.option = ^{
        
        UIActionSheet *picSheet = [[UIActionSheet alloc] initWithTitle:@"选择图片" delegate:selfVc cancelButtonTitle:@"取消" destructiveButtonTitle:nil otherButtonTitles:@"相机",@"相册", nil];
        
        [picSheet showInView:self.view];
    };
    
    if ([KYUserAccountTool shareUserData].headImg) {
        icon.imageViewStr = [KYUserAccountTool shareUserData].headImg;
    }
    
    self.icon = icon;
    
    KYSettingItem *nick = [KYSettingItem itemWithTitle:NSLocalizedString(@"昵称", nil)];
    nick.optionWithItem = ^(KYSettingArrowItem *nick) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"修改昵称" message:nil delegate:selfVc cancelButtonTitle:@"取消" otherButtonTitles:@"确定", nil];
        
        // 设置对话框的类型
        alert.alertViewStyle = UIAlertViewStylePlainTextInput;
        
        // 取得唯一的那个文本框,显示英雄的名称
        [alert textFieldAtIndex:0].text = nick.detailLabel;
        
        [alert show];
    };
    
    nick.detailLabel = [KYUserAccountTool shareUserData].userName;
    
    self.nick = nick;
    
    KYSettingItem *sex = [KYSettingItem itemWithTitle:NSLocalizedString(@"性别", nil)];
    sex.option = ^{
        KYRadioBoxChooseView *pickerChooseView = [[KYRadioBoxChooseView alloc] init];
        pickerChooseView.delegate = selfVc;
        pickerChooseView.dataArr = @[@"男",@"女"];
        pickerChooseView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [pickerChooseView performSelector:@selector(show) withObject:pickerChooseView afterDelay:0.35];
    };
    
    sex.detailLabel = [KYUserAccountTool shareUserData].userSex;
    
    self.sex = sex;

    KYSettingItem *birth = [KYSettingItem itemWithTitle:NSLocalizedString(@"生日", nil)];
    birth.option = ^{
        KYDatePickerView *datePickerView = [KYDatePickerView datePickerView];
        datePickerView.delegate = selfVc;
        datePickerView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
        [datePickerView performSelector:@selector(show) withObject:datePickerView afterDelay:0.35];

    };
    
    birth.detailLabel = [KYUserAccountTool shareUserData].userBirth;
    
    self.birth = birth;
    
    group.items = @[icon,nick,sex,birth];
}

#pragma mark - method
- (void)save
{
    if (!self.nick.detailLabel.length) {
        [MBProgressHUD showError:NSLocalizedString(@"昵称不能为空", nil)];
    } else {
        NSMutableArray *imageData = [NSMutableArray array];
        if (self.chooseImage) {
            [imageData addObject:self.chooseImage];
        }
        
        NSMutableDictionary *params = [NSMutableDictionary dictionary];
        params[@"name"] = self.nick.detailLabel;
        params[@"sex"] = self.sex.detailLabel;
        params[@"birth_month"] = self.birth.detailLabel;
        params[@"sign"] = self.textView.text;
        
        [JSTNewServer requestEditUserInfo:params getImageData:imageData success:^(NSDictionary *dataDic) {
            
            // 0.提示保存成功
            [MBProgressHUD showSuccess:NSLocalizedString(@"保存成功...", nil)];
            
            // 1.重新归档数据
            [KYUserAccountTool shareUserData].headImg = [NSString stringWithFormat:@"%@",dataDic[@"icon"]];
            [KYUserAccountTool shareUserData].userName = [NSString stringWithFormat:@"%@",dataDic[@"name"]];
            [KYUserAccountTool shareUserData].userSex = [NSString stringWithFormat:@"%@",dataDic[@"sex"]];
            [KYUserAccountTool shareUserData].userBirth = [NSString stringWithFormat:@"%@",dataDic[@"birth_month"]];
            [KYUserAccountTool shareUserData].userIntro = [NSString stringWithFormat:@"%@",dataDic[@"sign"]];
            [[KYUserAccountTool shareUserData] saveToSandBox];
            
            // 2.出栈当前控制器
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.5 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.navigationController popViewControllerAnimated:YES];
            });
            
        } error:^(NSString *errStr) {
            [MBProgressHUD showError:errStr];
        }];
    }
}

#pragma mark - KYDatePickerViewDelegate
- (void)datePickerView:(KYDatePickerView *)datePickerView didChooseDate:(NSString *)dateStr
{
    // 1.赋值文字
    self.birth.detailLabel = dateStr;
    
    // 2.刷新表格
    [self.tableView reloadData];
}

#pragma mark - KYRadioBoxChooseViewDelegate
- (void)radioBoxChooseView:(KYRadioBoxChooseView *)chooseView didChooseStr:(NSString *)str
{
    // 1.赋值文字
    self.sex.detailLabel = str;
    
    // 2.刷新表格
    [self.tableView reloadData];
}

#pragma mark - UIScrollViewDelegate
/**
 *  当滚动(一点儿)的时候就退出键盘
 */
- (void)scrollViewDidEndDragging:(UIScrollView *)scrollView willDecelerate:(BOOL)decelerate
{
    [self.textView endEditing:YES];
}

#pragma mark - UIAlertViewDelegate
- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) return;
    
    // 1.取得文本框最后的文字
    NSString *name = [alertView textFieldAtIndex:0].text;
    
    self.nick.detailLabel = name;
    
    [self.tableView reloadData];
}

#pragma mark - UIActionSheetDelegate
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [self openCamera];
            break;
            
        case 1:
            [self openPhotoLibrary];
            break;
            
        default:
            break;
    }
}

/**
 *  打开相机
 */
- (void)openCamera
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypeCamera;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}

/**
 *  打开相册
 */
- (void)openPhotoLibrary
{
    UIImagePickerController *ipc = [[UIImagePickerController alloc] init];
    ipc.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
    ipc.delegate = self;
    [self presentViewController:ipc animated:YES completion:nil];
}

#pragma mark - 图片选择控制器的代理
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    // 1.销毁picker控制器
    [picker dismissViewControllerAnimated:YES completion:nil];
    
    // 2.取得图片
    UIImage *image = info[UIImagePickerControllerOriginalImage];
    
    if (image) { // 给对应的item赋值
        
        // 3.赋值数据
        self.chooseImage = image;

        self.icon.imageViewStr = [NSString imageToBase64Str:image];
        
        [self.tableView reloadData];
    }
}

- (void)dealloc
{
    [KYNotificationCenter removeObserver:self];
}
@end
